package com.sun.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.dao.CheckinMapper;
import com.sun.dao.OrdersMapper;
import com.sun.dao.RoomMapper;
import com.sun.dao.RoomTypeMapper;
import com.sun.pojo.Checkin;
import com.sun.pojo.Orders;
import com.sun.pojo.Room;
import com.sun.pojo.RoomType;
import com.sun.service.CheckinService;
import com.sun.service.RoomTypeService;
import com.sun.utils.DataGridViewResult;
import com.sun.vo.CheckinVo;
import com.sun.vo.RoomTypeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CheckinServiceImpl implements CheckinService {

    @Autowired
    private CheckinMapper checkinMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private RoomTypeMapper roomTypeMapper;
    @Autowired
    private RoomMapper roomMapper;

    public DataGridViewResult list(CheckinVo checkinVo) {
        PageHelper.startPage(checkinVo.getPage(),checkinVo.getLimit());
        List<Checkin> checkinList=checkinMapper.list(checkinVo);
        PageInfo<Checkin> pageInfo = new PageInfo<Checkin>(checkinList);
        return new DataGridViewResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public int addCheckin(Checkin checkin) {
        // 1 添加入住数据
        checkin.setCreatedate(new Date());
        int addCheckinResult=checkinMapper.addCheckin(checkin);
        // 2 入住数据添加成功后
        if(addCheckinResult>0){
            //修改订单状态为已入住
            Orders orders=new Orders();
            orders.setId(checkin.getOrdersid());
            orders.setStatus(3);
            int ordersUpdateResult=ordersMapper.updateOrders(orders);
            //修改房间状态为已入住
            Room room = new Room();
            room.setId(checkin.getRoomid());
            room.setStatus(2);
            int roomUpdateResult=roomMapper.updateRoom(room);
            //修改房型已入住字段
            RoomType typeMapperById = roomTypeMapper.findById(checkin.getRoomtypeid());
            typeMapperById.setLivednum(typeMapperById.getLivednum()+1);
            if(typeMapperById.getRoomnum()==typeMapperById.getLivednum()){
                typeMapperById.setStatus(2);
            }
            int roomTypeUpdateResult=roomTypeMapper.updateRoomType(typeMapperById);

            if(ordersUpdateResult>0 && roomUpdateResult>0 && roomTypeUpdateResult>0){
                return 1;
            }
        }
        return 0;
    }
}
